package com.rr.middle;

/**
 * https://leetcode.cn/problems/string-to-integer-atoi/
 * 将字符串转换成一个 32 位有符号整数
 * 题不难  条件很多  纯恶心人的
 */
public class MyAtoi {
    public int myAtoi(String s) {
        int rate = 1;
        long tmp = 0L;
        boolean digitAppear = false;
        boolean rateAppear = false;
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                tmp = tmp * 10 + c - 48;
                digitAppear = true;
            } else  {
                if (c == ' ' && !digitAppear && !rateAppear) {
                    continue;
                } else if (c == '-' && !digitAppear && !rateAppear) {
                    rate = -1;
                    rateAppear = true;
                } else if(c == '+' && !digitAppear && !rateAppear){
                    rateAppear = true;
                } else {
                    break;
                }
            }
            if (rate == 1 && tmp >= Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            }
            if (rate == -1 && -tmp <= Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
            }
        }
        return ((int)(tmp * rate));
    }

    public static void main(String[] args) {
        MyAtoi myAtoi = new MyAtoi();
        System.out.println(myAtoi.myAtoi("+1"));
    }
}
